package org.jeecg.hr.service.impl;

import java.io.Serializable;
import java.util.Collection;

import javax.transaction.Transactional;

import org.jeecg.hr.entity.SalaryTemplate;
import org.jeecg.hr.entity.SalaryTemplateDetail;
import org.jeecg.hr.mapper.SalaryTemplateDetailMapper;
import org.jeecg.hr.mapper.SalaryTemplateMapper;
import org.jeecg.hr.service.SalaryTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class SalaryTemplateServiceImpl extends ServiceImpl<SalaryTemplateMapper, SalaryTemplate> implements SalaryTemplateService {

	@Autowired
	private SalaryTemplateMapper salaryTemplateMapper;
	@Autowired
	private SalaryTemplateDetailMapper salaryTemplateDetailMapper;
	
	@Override
	@Transactional
	public void delSalaryTemplate(String id) {
		SalaryTemplate salaryTemplate = salaryTemplateMapper.selectById(id);
		salaryTemplateDetailMapper.deleteByTemplateCode(salaryTemplate.getTemplateCode());
		salaryTemplateMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			SalaryTemplate salaryTemplate = salaryTemplateMapper.selectById(id);
			salaryTemplateDetailMapper.deleteByTemplateCode(salaryTemplate.getTemplateCode());
			salaryTemplateMapper.deleteById(id);
		}
	}
	
	@Override
	@Transactional
	public void saveSalaryTemplateWithDetail(SalaryTemplate salaryTemplate) {
		salaryTemplateMapper.insert(salaryTemplate);
		if(salaryTemplate.getSalaryTemplateDetails() != null && salaryTemplate.getSalaryTemplateDetails().size() > 0) {
			for(SalaryTemplateDetail entity:salaryTemplate.getSalaryTemplateDetails()) {
				entity.setTemplateCode(salaryTemplate.getTemplateCode());
				salaryTemplateDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateSalaryTemplateWithDetail(SalaryTemplate salaryTemplate) {
		salaryTemplateMapper.updateById(salaryTemplate);
		
		//1.先删除子表数据
		salaryTemplateDetailMapper.deleteByTemplateCode(salaryTemplate.getTemplateCode());
		
		//2.子表数据重新插入
		if(salaryTemplate.getSalaryTemplateDetails() !=null && salaryTemplate.getSalaryTemplateDetails().size()>0) {
			for(SalaryTemplateDetail entity : salaryTemplate.getSalaryTemplateDetails()) {
				entity.setTemplateCode(salaryTemplate.getTemplateCode());
				salaryTemplateDetailMapper.insert(entity);
			}
		}
	}

}

